package com.etone.smartAudit.service;

import cn.hutool.core.util.XmlUtil;
import com.alibaba.fastjson.JSON;
import com.etone.smartAudit.domain.PUumOrganizationinfo;
import com.etone.smartAudit.domain.PUumUserinfo;
import com.etone.smartAudit.vo.PortalBaseVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.springframework.beans.factory.annotation.Value;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.rpc.*;
import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * usd用户组织对接
 */
@Slf4j
@org.springframework.stereotype.Service
public class UDSService {

    @Value("${uds.appId:8b3f632023474660ab53d82600c109e6}")
    private String appId;

    @Value("${uds.pwd:GMCCSJZT}")
    private String pwd;

    @Value("${uds.wslUrl:http://10.251.147.187:7001/gd_uum/axis/BizService?wsdl}")
    private String wslUrl;

    private static final int ORG_TYPE = 0x00001;
    private static final int EMPLOYEE_TYPE = 0x00002;

    private String getInputXml(String logId) {
        String xml = "<?xml version=\\\"1.0\\\" encoding=\\\"GBK\\\"?>\n<root>\n" +
                "\t\t\t\t<data>\n" +
                "\t\t\t\t<APPLICATION>\n" +
                "\t\t\t\t<APPID>" + appId + "</APPID>\n" +
                "\t\t\t\t<WEBSERVICEPWD>" + pwd + "</WEBSERVICEPWD>\n" +
                "\t\t\t\t</APPLICATION>\n" +
                "\t\t\t\t<EOSORG_T_EMPLOYEE_LOG>\n" +
                "\t\t\t\t<logID>" + logId + "</logID>\n" +
                "\t\t\t\t</EOSORG_T_EMPLOYEE_LOG>\n" +
                "\t\t\t\t</data>\n" +
                "\t\t\t\t</root>";
        return xml;
    }

    public String baseRequest(String inputXML, String processName, Integer type) throws Exception {
        String packageName = "webservice";
        String unitID = "0";
        String automata = processName;
        Service service = new Service();
        Call call = (Call) service.createCall();
        //设置服务地址
        call.setTargetEndpointAddress(wslUrl);
        //设置操作名
        call.setOperationName("runBiz");
        //设置入口参数
        call.addParameter("packageName", XMLType.XSD_STRING, ParameterMode.IN);
        call.addParameter("unitId", XMLType.XSD_STRING, ParameterMode.IN);
        call.addParameter("processName", XMLType.XSD_STRING, ParameterMode.IN);
        call.addParameter("password", XMLType.XSD_STRING, ParameterMode.IN);
        call.addParameter("bizDataXML", XMLType.XSD_STRING, ParameterMode.IN);
        call.setReturnType(XMLType.XSD_STRING);
        //调用
        String returnStr = (String) call.invoke(new Object[]{packageName, unitID, automata, pwd, inputXML});
        return returnStr;
    }

    /***
     * 获取用户异动信息
     */
    public PortalBaseVo<PUumUserinfo> bizQueryEmpChgHistory(String logId) throws Exception {
        String inputXML = "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
                "<root><data>\n" +
                "<APPLICATION>\n" +
                "<APPID>" + appId + "</APPID>\n" +
                "<WEBSERVICEPWD>" + pwd + "</WEBSERVICEPWD>\n" +
                "</APPLICATION>\n" +
                "<EOSORG_T_EMPLOYEE_LOG>\n" +
                "<logID>" + logId + "</logID>\n" +
                "</EOSORG_T_EMPLOYEE_LOG>\n" +
                "</data></root>";
        //调用
        String returnStr = baseRequest(inputXML, "biz.bizQueryEmpChgHistory", EMPLOYEE_TYPE);
        System.out.println("returnStr:" + returnStr);
        DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = documentBuilder.parse(new ByteArrayInputStream(returnStr.getBytes()));
        NodeList nodeList = document.getElementsByTagName("EOSORG_V_EMPLOYEE_LOG");
        String continuFlag = document.getElementsByTagName("continueFlag").item(0).getTextContent();
        int size = nodeList.getLength();
        List<PUumUserinfo> list = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            Map<String, Object> map = XmlUtil.xmlToMap(nodeList.item(i));
            PUumUserinfo pUumUserinfo = JSON.parseObject(JSON.toJSONString(map), PUumUserinfo.class);
            list.add(pUumUserinfo);
        }
        PortalBaseVo<PUumUserinfo> portalBaseVo = new PortalBaseVo();
        portalBaseVo.setList(list);
        portalBaseVo.setContinuFlag(continuFlag);
        return portalBaseVo;
    }

    public String bizQueryEmpChgHistoryV2(String logId) throws Exception {
        String xml = "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
                "<root><data>\n" +
                "<APPLICATION><APPID>" + appId + "</APPID>\n" +
                "<WEBSERVICEPWD>" + pwd + "</WEBSERVICEPWD>\n" +
                "</APPLICATION>\n" +
                "<EOSORG_T_EMPLOYEE_LOG>\n" +
                "<logID criteria=\"between\">" + logId + "</logID>\n" +
                "</EOSORG_T_EMPLOYEE_LOG>\n" +
                "</data></root>";
        String result = baseRequest(xml, " biz.bizQueryEmpChgHistoryV2", EMPLOYEE_TYPE);
        return result;
    }

    public String bizQueryEmployeeV2(String orgId) throws Exception {
        String xml = "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
                "<root><data>\n" +
                "<APPLICATION>\n" +
                "<APPID>" + appId + "</APPID>\n" +
                "<WEBSERVICEPWD>" + pwd + "</WEBSERVICEPWD>\n" +
                "</APPLICATION>\n" +
                "<EOSORG_T_Employee>\n" +
                "<orgID>00A63DE1DA454317A512EE77DB35E5C5</orgID>\n" +
                "<employee></employee >\n" +
                "<userID></ userID >\n" +
                "<fullsyncNO criteria=\"between\">" + orgId + "</ fullsyncNO >\n" +
                "</EOSORG_T_Employee>\n" +
                "</data></root>";
        String result = baseRequest(xml, "biz.bizQueryEmployeeV2", EMPLOYEE_TYPE);
        return result;
    }

    /***
     * 获取用户最新信息
     */
    public String bizQueryEmployee(String orgId) throws Exception {
        String xml = "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
                "<root><data>\n" +
                "<APPLICATION>\n" +
                "<APPID>" + appId + "</APPID>\n" +
                "<WEBSERVICEPWD>" + pwd + "</WEBSERVICEPWD>\n" +
                "</APPLICATION>\n" +
                "<EOSORG_T_Employee>\n" +
                "<orgID></orgID>\n" +
                "<employee></employee >\n" +
                "<userID></ userID >\n" +
                "<fullsyncNO criteria=\"between\">1:500</ fullsyncNO >\n" +
                "</EOSORG_T_Employee>\n" +
                "</data></root>";
        String result = baseRequest(xml, "biz.bizQueryOrganization", EMPLOYEE_TYPE);
        return result;
    }

    /**
     * 获取组织最新信息
     */
    public String bizQueryOrganization(String param) throws Exception {
        String xml = "<?xml version=\"1.0\" encoding=\"GBK\"?> //注意此句话千万不能漏掉，否则不能正确调用\n" +
                "WEBSERVICE\n" +
                "<root><data>\n" +
                "<APPLICATION>\n" +
                "<APPID>" + appId + "</APPID>\n" +
                "<WEBSERVICEPWD>" + pwd + "</WEBSERVICEPWD>\n" +
                "</APPLICATION>\n" +
                "<EOSORG_T_Organization>\n" +
                "<orgID></orgID>\n" +
                "</EOSORG_T_Organization>\n" +
                "</data></root>";
        String reslut = baseRequest(xml, "biz.bizQueryOrganization", ORG_TYPE);
        return reslut;
    }

    /***
     * 获取组织异动信息
     */
    public  PortalBaseVo<PUumOrganizationinfo> bizQueryOrgChgHistory(String param) throws Exception {
        String xml = "<?xml version=\"1.0\" encoding=\"GBK\"?>\n" +
                "<root><data>\n" +
                "<APPLICATION>\n" +
                "<APPID>" + appId + "</APPID> \n" +
                "<WEBSERVICEPWD>" + pwd + "</WEBSERVICEPWD>\n" +
                "</APPLICATION>\n" +
                "<EOSORG_T_ORGANIZATION_LOG>\n" +
                "<logID criteria=\"between\">" + param + "</logID>\n" +
                "</EOSORG_T_ORGANIZATION_LOG>\n" +
                "</data></root>";
        String result = baseRequest(xml, "biz.bizQueryOrgChgHistory", ORG_TYPE);
        DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = documentBuilder.parse(new ByteArrayInputStream(result.getBytes()));
        NodeList nodeList = document.getElementsByTagName("EOSORG_V_ORGANIZATION_LOG");
        String continuFlag = document.getElementsByTagName("continueFlag").item(0).getTextContent();
        List<PUumOrganizationinfo> list = new ArrayList<>();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Map<String, Object> map = XmlUtil.xmlToMap(nodeList.item(i));
            PUumOrganizationinfo info = JSON.parseObject(JSON.toJSONString(map), PUumOrganizationinfo.class);
//            organizationinfoService.save(info);
            list.add(info);
        }
        PortalBaseVo<PUumOrganizationinfo> vo = new PortalBaseVo<>();
        vo.setContinuFlag(continuFlag);
        vo.setList(list);
        return vo;
    }
}
